package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qk.common.PageResult;
import com.qk.constant.BusinessStatusConstants;
import com.qk.constant.ClueStatusConstants;
import com.qk.dto.business.BusinessDTO;
import com.qk.dto.business.BusinessFollowDTO;
import com.qk.dto.business.BusinessHighSeasDTO;
import com.qk.dto.business.BusinessQueryDTO;
import com.qk.entity.Business;
import com.qk.entity.BusinessTrackRecord;
import com.qk.entity.Clue;
import com.qk.entity.User;
import com.qk.enums.ParamEnum;
import com.qk.exception.CommonException;
import com.qk.management.mapper.BusinessMapper;
import com.qk.management.mapper.BusinessTrackRecordMapper;
import com.qk.management.mapper.ClueMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.BusinessService;
import com.qk.utils.CurrentUserContextHolders;
import com.qk.vo.business.BusinessQueryVO;
import com.qk.vo.business.BusinessVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 *
 * @author lyl
 * @created 2025/10/15 11:47
 * @description
 *
 */
@Service
@SuppressWarnings("all")
public class BusinessServiceImpl extends ServiceImpl<BusinessMapper, Business> implements BusinessService {
    @Autowired
    private ClueMapper clueMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BusinessTrackRecordMapper businessTrackRecordMapper;
    @Override
    public PageResult<BusinessQueryVO> getListByPage(BusinessQueryDTO businessQueryDTO) {
        Page<BusinessQueryVO> list = this.baseMapper.getListPage(Page.of(businessQueryDTO.getPage(), businessQueryDTO.getPageSize()),businessQueryDTO);
        return PageResult.<BusinessQueryVO>builder()
                .total(Long.valueOf(list.getTotal()).intValue())
                .rows(list.getRecords())
                .build();
    }

    @Override
    public void addBusiness(BusinessDTO businessDTO) {
        Business business = BeanUtil.copyProperties(businessDTO, Business.class);
        business.setStatus(BusinessStatusConstants.WAIT_ALLOCATION);
        business.setCreateTime(LocalDateTime.now());
        business.setUpdateTime(LocalDateTime.now());
        this.baseMapper.insert(business);
    }

    @Override
    public void assignBusiness(Integer businessId, Integer userId) {
        this.baseMapper.update(Wrappers.lambdaUpdate(Business.class).set(Business::getUserId, userId)
                .set(Business::getStatus, BusinessStatusConstants.WAIT_FOLLOW_UP)
                .set(Business::getUpdateTime, LocalDateTime.now())
                .eq(Business::getId, businessId));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void backHighSeas(Integer id) {
        Business business = this.baseMapper.selectById(id);
        if (ObjectUtil.isEmpty(business)){
            CommonException.throwCommonException(ParamEnum.PARAM_NOT_EXIST);
        }
        this.baseMapper.update(Wrappers.lambdaUpdate(Business.class)
                .set(Business::getStatus, BusinessStatusConstants.RECOVERY_HIGH_SEAS)
                .set(Business::getUpdateTime, LocalDateTime.now())
                .eq(Business::getId, id));
        if (ObjectUtil.isNotNull(business.getClueId())){
            clueMapper.update(Wrappers.lambdaUpdate(Clue.class)
                    .set(Clue::getStatus, ClueStatusConstants.FAKE_CLUE)
                    .set(Clue::getUpdateTime, LocalDateTime.now())
                    .set(Clue::getNextTime, null)
                    .eq(Clue::getId, business.getClueId()));
        }
    }
    @Override
    public BusinessVO getBusinessById(Integer id) {
        Business business = this.baseMapper.selectById(id);
        BusinessVO businessVO = null;
        if (ObjectUtil.isNotNull(business)){
            businessVO = BeanUtil.copyProperties(business, BusinessVO.class);
        }
        List<BusinessTrackRecord> businessTrackRecords = businessTrackRecordMapper.selectList(Wrappers.lambdaQuery(BusinessTrackRecord.class).eq(BusinessTrackRecord::getBusinessId, id));
        List<BusinessVO.TrackRecordsVO> trackRecordsVOStream = null;
        if (CollUtil.isNotEmpty(businessTrackRecords)){
            User user = userMapper.getUserById(business.getUserId());
            trackRecordsVOStream = businessTrackRecords.stream().map(businessTrackRecord ->{
                        BusinessVO.TrackRecordsVO bt = BeanUtil.copyProperties(businessTrackRecord, BusinessVO.TrackRecordsVO.class);
                        bt.setAssignName(user.getName());
                        String keyItems = businessTrackRecord.getKeyItems();
                        bt.setKeyItems(Arrays.stream(keyItems.substring(1,keyItems.length()-1).split( ",")).toList());
                        return bt;
                    }).toList();
        }
        businessVO.setTrackRecords(trackRecordsVOStream);
        return businessVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void followBusiness(BusinessFollowDTO businessFollowDTO) {
        BusinessTrackRecord br = BeanUtil.copyProperties(businessFollowDTO, BusinessTrackRecord.class);
        br.setId(null);
        br.setBusinessId(businessFollowDTO.getId());
        br.setUserId(CurrentUserContextHolders.get());
        br.setKeyItems(businessFollowDTO.getKeyItems().toString());
        br.setCreateTime(LocalDateTime.now());
        businessTrackRecordMapper.insert(br);
        Business business = BeanUtil.copyProperties(businessFollowDTO, Business.class);
        business.setStatus(BusinessStatusConstants.FOLLOW_UP);
        business.setUpdateTime(LocalDateTime.now());
        business.setUserId(CurrentUserContextHolders.get());
        this.baseMapper.updateById(business);
    }

    @Override
    public PageResult<Business> getHighSeasList(BusinessHighSeasDTO businessHighSeasDTO) {
        Page<Business> list = this.baseMapper.getHighSeasList(Page.of(businessHighSeasDTO.getPage(), businessHighSeasDTO.getPageSize()),businessHighSeasDTO);
        return PageResult.<Business>builder()
                .total(Long.valueOf(list.getTotal()).intValue())
                .rows(list.getRecords())
                .build();
    }
}
